package com.alison.module.authors.mapper;

import com.alison.module.authors.domain.param.UserParam;
import com.alison.module.authors.entity.User;
import com.alison.module.authors.typehandler.EnumsTypeHandler;
import com.alison.module.authors.enums.UserSexEnum;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.UpdateProvider;
import org.apache.ibatis.type.JdbcType;

import java.util.List;
import java.util.Map;

@Mapper
public interface UserMapper {

    @Select("SELECT * FROM user")
    @Results({
            @Result(property = "userSex", column = "user_sex", javaType = UserSexEnum.class, jdbcType = JdbcType.TINYINT, typeHandler = EnumsTypeHandler.class),
            @Result(property = "nickName", column = "nick_name", javaType = String.class)})
    List<User> getAll();

    @SelectProvider(type = UserSql.class, method = "getList")
    List<User> getList(UserParam userParam);

    @SelectProvider(type = UserSql.class, method = "getCount")
    int getCount(UserParam userParam);

    /*注意$与#的区别*/

    @Select("SELECT * FROM user WHERE user_sex = #{userSex}")
    List<User> getListByUserSex(@Param("userSex") String userSex);

    @Select("SELECT * FROM user WHERE user_name=#{username} AND user_sex = #{usersex}")
    List<User> getListByNameAndSex(Map<String, Object> map);

    @Select("SELECT * FROM user WHERE ID = #{id}")
    @Results({@Result(property = "userSex", column = "user_sex", javaType = UserSexEnum.class),
            @Result(property = "nickName", column = "nick_name", javaType = String.class)})
    User getOne(Long id);

    @Insert("INSERT INTO user(user_name,pass_word,user_sex) VALUES(#{userName},#{passWord}," +
            "#{userSex, " +
            "javaType = com.alison.module.authors.enums.UserSexEnum, " +
            "jdbcType = TINYINT,  " +
            "typeHandler = com.alison.module.authors.typehandler.EnumsTypeHandler})")
    void insert(User user);

    @UpdateProvider(type = UserSql.class, method = "update")
    int update(User user);

    @Update({
            "<script> ",
            "UPDATE user ",
            "<set>",
            " <if test='userName != null'>userName=#{userName},</if>",
            " <if test='nickName != null'>nick_name=#{nickName},</if>",
            " </set> ",
            "where id=#{id} ",
            "</script>"
    })
    int updateUser(User user);

    @Delete("DELETE FROM user WHERE id = #{id}")
    int delete(Long id);

}
